#include <QSqlDatabase>
#include <QSqlError>
#include <QDebug>
#include <QSqlQuery>
#include <QApplication>

#include "dbreader.h"

class DbReaderPrivate
{
public:
    QSqlDatabase db;
};

DbReader::DbReader(QObject *parent) : QObject(parent)
{
    QString dbPath = QString("%1/hahaimages.db").arg(qApp->applicationDirPath());
    d_ptr = new DbReaderPrivate;
    d_ptr->db = QSqlDatabase::addDatabase("QSQLITE");
    d_ptr->db.setDatabaseName(dbPath);

    if (!d_ptr->db.open()) {
        qDebug() << "failed to open sqlite file for reading." << d_ptr->db.lastError().text();
    }
}

DbReader::~DbReader()
{
    delete d_ptr;
}

DbReader* DbReader::instance()
{
    static DbReader _inst;
    return &_inst;
}

QList<ImageData> DbReader::queryGoodImages()
{
    QList<ImageData> imageDataList;
    QSqlQuery query;
    if (query.exec("SELECT * FROM haha_good_images")) {
        while (query.next()) {
            imageDataList.append(ImageData {query.value(0).toString(), query.value(1).toString()});
        }
    } else {
        qDebug() << "Error: " << query.lastError().text();
    }
    return imageDataList;
}

QList<ImageData> DbReader::queryNewImages()
{
    QList<ImageData> imageDataList;
    QSqlQuery query;
    if (query.exec("SELECT * FROM haha_new_images")) {
        while (query.next()) {
            imageDataList.append(ImageData {query.value(0).toString(), query.value(1).toString()});
        }
    } else {
        qDebug() << "Error: " << query.lastError().text();
    }
    return imageDataList;
}

